import { sendMessage, chunkArray } from "../utils";

let tempAntiContent: any = "";
let unToConfirmPriceReviewOrderCount = 0;
let temuDisplayPriceMultiplier = 1;

// 列表名接口
function getPageDataUrl() {
  return `${location.origin}/api/kiana/mms/robin/searchForSemiSupplier`;
}
// sku详情接口
function getSkuDataUrl() {
  return `${location.origin}/api/kiana/magnus/mms/price/bargain-no-bom/batch/info/query`;
}
// 同意建议价接口
function getDoAgreeToNegotiateUrl() {
  return `${location.origin}/api/kiana/magnus/mms/price/bargain-no-bom/batch`;
}

// 获取当前页数
function getCurrentPage() {
  return Number(
    document.querySelector('[class*="pagerItemActive"]')?.textContent || 1
  );
}
function getErpSkuMathField() {
  return "skuNoGenerate";
}

// 从ERP获取sku的采购价的时候需要乘上赔率
function formatSourcePrice(price: any) {
  return price * temuDisplayPriceMultiplier;
}

// 获取PageSize
function getPageSize() {
  const pageSizeText =
    document.querySelector(
      '[data-testid="beast-core-pagination"] [class*="mirror"]'
    )?.textContent || "";
  return Number(pageSizeText.match(/^\d+/)?.[0] || 10);
}

function getAntiContent() {
  if (tempAntiContent) {
    return Promise.resolve(tempAntiContent);
  }
  return sendMessage({
    type: "getAntiContent",
  }).then((data) => {
    tempAntiContent = data || "";
  });
}

function getRequestHeaders() {
  const mallId = localStorage.getItem("agentseller-mall-info-id") || "";
  return {
    "Content-Type": "application/json",
    "Anti-Content": tempAntiContent,
    Mallid: mallId,
  };
}

// 获取总页数
function getTotalPageSize() {
  const endPageElement = document
    .querySelector('[data-testid="beast-core-pagination"]')
    ?.querySelector('[class*="pagerItem"]:nth-last-child(2)');

  return Number(endPageElement?.textContent || 1);
}
// 格式化列表数据
function formatListDataToMap({
  data,
  skuCodeList,
  productBySkuAndCostPriceMap,
}: {
  data: any[];
  skuCodeList: any[];
  productBySkuAndCostPriceMap: any;
}) {
  return data.reduce((obj, dataItem: any) => {
    const { id, skuInfoList } = dataItem;
    if (id && skuInfoList && skuInfoList.length) {
      obj[id] = {
        priceOrderId: id,
        skuPriceMap: {},
        items: [],
      };
      skuInfoList.forEach((skuItem: any) => {
        const {
          spec,
          productSkuExtCode,
          suggestSupplyPrice,
          priceBeforeExchange,
          productSkuId,
        } = skuItem;
        const key = productSkuExtCode || spec;
        obj[id].skuPriceMap[key] = suggestSupplyPrice;
        obj[id].items.push({
          productSkuId,
          price: suggestSupplyPrice,
        });
        skuCodeList.push(key);
        productBySkuAndCostPriceMap[key] = priceBeforeExchange;
      });
    }

    return obj;
  }, {});
}

const getDataIndexPriceMultiplier = (data: any, index: any) => {
  let priceMultiplier = 0;
  const siteSupplierPriceInfo =
    data[index]?.skcList?.[0]?.skuList?.[0]?.siteSupplierPriceList?.[0];
  if (siteSupplierPriceInfo) {
    const { supplierPrice, supplierPriceValue } = siteSupplierPriceInfo;
    if (supplierPrice && supplierPriceValue) {
      const numberMatch = supplierPrice.match(/\d+\.\d+/);
      // 提取匹配到的数字并转换为数值类型
      const number = numberMatch ? parseFloat(numberMatch[0]) : null;
      if (number) {
        priceMultiplier = supplierPriceValue / number;
      }
    }
  }
  return Math.round(priceMultiplier);
};

// 获取商品列表中的信息
async function getProductBySkuMap({
  pageNum = 1,
  pageSize = 10,
  skuCodeList = [],
  productBySkuAndCostPriceMap = {},
}: {
  pageNum: number;
  pageSize: number;
  skuCodeList: any[];
  productBySkuAndCostPriceMap: any;
}) {
  const pageDataUrl = getPageDataUrl();
  await getAntiContent();
  const headers = getRequestHeaders();
  const skcResponse = await fetch(pageDataUrl, {
    method: "POST",
    headers,
    body: JSON.stringify({
      pageNum,
      pageSize,
      priceReviewStatusList: [3, 2, 0, 1],
      secondarySelectStatusList: [7],
      supplierTodoTypeList: [1],
    }),
  }).then((res) => res.json());
  const skcData = skcResponse?.result?.dataList || [];
  if (skcData.length) {
    temuDisplayPriceMultiplier = 0;
    const firstIndexMultiplier = getDataIndexPriceMultiplier(skcData, 0);
    if (firstIndexMultiplier) {
      if (skcData.length > 1) {
        const secondIndexMultiplier = getDataIndexPriceMultiplier(skcData, 1);
        if (firstIndexMultiplier === secondIndexMultiplier) {
          temuDisplayPriceMultiplier = firstIndexMultiplier;
        } else {
          alert("价格比例不一致");
          throw new Error("价格比例不一致");
        }
      } else {
        temuDisplayPriceMultiplier = firstIndexMultiplier;
      }
    }
  }
  if (!temuDisplayPriceMultiplier) {
    alert("获取不到价格比例");
    throw new Error("获取不到价格比例");
  }
  const orderIds = skcData.reduce((list: any[], dataItem: any) => {
    const { skcList, hasToConfirmPriceReviewOrder } = dataItem;
    if (hasToConfirmPriceReviewOrder) {
      (skcList || []).forEach((skcItem: any) => {
        skcItem.supplierPriceReviewInfoList.forEach(
          (supplierPriceReviewInfo: any) => {
            const { priceOrderId } = supplierPriceReviewInfo;
            list.push(priceOrderId);
          }
        );
      });
    } else {
      unToConfirmPriceReviewOrderCount++;
    }

    return list;
  }, []);
  if (!orderIds.length) {
    return {};
  }

  const skuDataUrl = getSkuDataUrl();
  const skuResponse = await fetch(skuDataUrl, {
    method: "POST",
    headers,
    body: JSON.stringify({
      orderIds,
    }),
  }).then((res) => res.json());
  const data = skuResponse.result.priceReviewItemList;

  return formatListDataToMap({
    data,
    skuCodeList,
    productBySkuAndCostPriceMap,
  });
}

// 操作时格式化数据
function formatSaveParams({
  productBySkuMap,
  skuPurchasePriceMap,
  multiplier,
}: {
  productBySkuMap: any;
  skuPurchasePriceMap: any;
  multiplier: number;
}) {
  const itemRequests: any[] = [];
  const totalMathSkuId: any[] = [];
  let successTotal = unToConfirmPriceReviewOrderCount;
  let failTotal = 0;
  let skipCount = 0;
  unToConfirmPriceReviewOrderCount = 0;
  for (const key of Object.keys(productBySkuMap)) {
    const { priceOrderId, skuPriceMap, items } = productBySkuMap[key];
    let isAllSkuMatch = true;
    let isSkip = false;
    for (const skuCode of Object.keys(skuPriceMap)) {
      const hasErpData = skuCode in skuPurchasePriceMap;
      if (!hasErpData) {
        isSkip = true;
        break;
      }
      const skuPriceNumber = Number(skuPriceMap[skuCode]);
      const contrastNumber =
        Number(skuPurchasePriceMap[skuCode]) * Number(multiplier);
      const inMathRule = skuPriceNumber > contrastNumber;
      if (!inMathRule) {
        isAllSkuMatch = false;
      }
    }
    if (isSkip) {
      skipCount++;
    } else {
      let supplierResult = isAllSkuMatch ? 1 : 3;
      if (isAllSkuMatch) {
        items.forEach((item: any) => {
          totalMathSkuId.push(item.productSkuId);
        });
        successTotal++;
      } else {
        failTotal++;
      }
      const formatItems = items.map((item: any) => {
        if (isAllSkuMatch) {
          return item;
        }
        const { price, ...otherItemInfo } = item;
        return {
          ...otherItemInfo,
        };
      });
      itemRequests.push({
        priceOrderId,
        supplierResult,
        items: formatItems,
      });
    }
  }
  temuDisplayPriceMultiplier = 0;
  if (!itemRequests.length) {
    return { paramsList: [], successTotal, failTotal, skipCount };
  }
  const paramsList = chunkArray(itemRequests, 2000).map((item) => {
    return {
      itemRequests: item,
    };
  });
  return { paramsList, successTotal, failTotal, skipCount };
}

export default {
  getCurrentPage,
  getPageSize,
  getTotalPageSize,
  getProductBySkuMap,
  formatSaveParams,
  getDoAgreeToNegotiateUrl,
  getRequestHeaders,
  getErpSkuMathField,
  formatSourcePrice,
};
